﻿using System;
using System.Collections.Generic;

public static partial class Tools
{
    /// <summary>
    /// 从数组中随机取一个元素
    /// </summary>
    public static T RandomElement<T>(T[] array)
    {
        if (array == null || array.Length <= 0)
            throw new System.Exception("获取随机元素失败：空的数组引用或数组元素不存在");
        return array[UnityEngine.Random.Range(0, array.Length)];
    }

    /// <summary>
    /// 从数组中随机取一个元素
    /// </summary>
    public static T RandomElement<T>(IList<T> list)
    {
        if (list == null || list.Count <= 0)
            throw new System.Exception("获取随机元素失败：空的数组引用或数组元素不存在");
        return list[UnityEngine.Random.Range(0, list.Count)];
    }

    /// <summary>
    /// 从数组中随机取出任意数量的不同元素
    /// </summary>
    public static List<T> RandomSubList<T>(List<T> list, int count)
    {
        var result = new List<T>();
        if (count <= 0)
            return result;
        if (count > list.Count)
            count = list.Count;
        var tempList = new List<T>(list);
        while (result.Count < count)
        {
            var randomIndex = UnityEngine.Random.Range(0, tempList.Count);
            result.Add(tempList[randomIndex]);
            tempList.RemoveAt(randomIndex);
        }
        return result;
    }

    /// <summary>
    /// 在[min, max)范围内生成count个不重复的随机数
    /// </summary>
    public static List<int> RandomNoRepeat(int min, int max, int count)
    {
        var maxCount = max - min;
        if (count > maxCount)
            count = maxCount;
        var randonNums = new HashSet<int>();
        while (randonNums.Count < count)
            randonNums.Add(UnityEngine.Random.Range(min, max));// HashSet会自动处理重复元素
        return new List<int>(randonNums);
    }

    /// <summary>
    /// 随机枚举
    /// </summary>
    public static T RandomEnum<T>() where T : Enum
    {
        var type = typeof(T);
        return RandomElement(Enum.GetValues(type) as T[]);
    }

    /// <summary>
    /// 获取百分比随机概率
    /// </summary>
    public static bool PercentageProbability(int probability)
    {
        return UnityEngine.Random.Range(0, 100) < probability;
    }

    /// <summary>
    /// 获取百分比随机概率
    /// </summary>
    public static bool PercentageProbability(float probability)
    {
        return UnityEngine.Random.Range(0, 100f) < probability;
    }
}